import os
import shutil
import uuid

from fastapi import Request
from fastapi import APIRouter, UploadFile, File

from core.exception.errors import ErrorException
from core.response import create_response
from conf.config import app_config

common_router = APIRouter()


@common_router.post("/upload_image")
async def upload_image(request: Request, file: UploadFile = File(...)):
    # 生成唯一文件名并指定文件后缀
    file_ext = os.path.splitext(file.filename)[1]
    allowed_exts = (".jpg", ".jpeg", ".png")
    if file_ext not in allowed_exts:
        raise ErrorException('只能上传图片')
    file_name = str(uuid.uuid4()) + file_ext

    # 保存上传的文件到指定文件夹中
    file_path = os.path.join(f"{app_config.STATIC_DIR}/uploads", file_name)
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)

    return create_response({"filename": f"{request.base_url}static/uploads/{file_name}"})
